package com.xuecheng.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.base.exception.XueChengPlusException;
import com.xuecheng.content.mapper.CourseTeacherMapper;
import com.xuecheng.content.model.po.CourseTeacher;
import com.xuecheng.content.service.CourseTeacherService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CourseTeacherServiceImpl extends ServiceImpl<CourseTeacherMapper, CourseTeacher> implements CourseTeacherService {

    @Autowired
    private CourseTeacherMapper courseTeacherMapper;

    /**
     * 查询教师列表信息
     *
     * @param courseId 课程id
     * @return
     */
    @Override
    public List<CourseTeacher> findTeacherList(Long courseId) {
        // 条件构造器
        LambdaQueryWrapper<CourseTeacher> queryWrapper = new LambdaQueryWrapper<>();
        // 构造条件
        queryWrapper.eq(CourseTeacher::getCourseId, courseId);
        // 查询数据库并返回
        return courseTeacherMapper.selectList(queryWrapper);
    }

    /**
     * 添加/修改教师信息
     *
     * @param courseTeacher 课程教师信息
     * @return
     */
    @Override
    public CourseTeacher saveCourseTeacher(CourseTeacher courseTeacher) {
        // 获取教师id
        Long teacherId = courseTeacher.getId();

        if (teacherId == null) {
            // 新增
            int inserted = courseTeacherMapper.insert(courseTeacher);
            // 判断新增是否成功
            if (inserted != 1) XueChengPlusException.cast("新增教师信息失败");
        } else {
            // 修改
            // 根据教师id查询数据库
            CourseTeacher courseTeacherInfo = courseTeacherMapper.selectById(teacherId);
            // 对象拷贝
            BeanUtils.copyProperties(courseTeacher, courseTeacherInfo);
            // 更新数据库
            int updated = courseTeacherMapper.updateById(courseTeacherInfo);
            // 判断是否更新成功
            if (updated != 1) XueChengPlusException.cast("修改教师信息失败");
        }

        // 查询刚刚新增、修改的教师信息，并返回
        return courseTeacherMapper.selectById(courseTeacher.getId());
    }

    /**
     * 删除教师信息
     *
     * @param courseId  课程id
     * @param teacherId 教师id
     */
    @Override
    public void deleteCourseTeacher(Long courseId, Long teacherId) {
        // 条件构造器
        LambdaUpdateWrapper<CourseTeacher> updateWrapper = new LambdaUpdateWrapper<>();
        // 构造条件
        updateWrapper.eq(CourseTeacher::getCourseId, courseId).eq(CourseTeacher::getId, teacherId);
        // 操作数据库，执行删除
        int deleted = courseTeacherMapper.delete(updateWrapper);
        // 判断删除是否成功
        if (deleted != 1) XueChengPlusException.cast("删除教师信息失败");
    }
}
